package dao;

import entidad.Lote;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

public class LoteDAO {
    
    private EntityManagerFactory emf = JPAUtil.getEntityManagerFactory();
    
    public void crear(Lote object) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        try {
            em.persist(object);
            em.flush();//newline
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }

    public boolean eliminar(Lote object) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        boolean ret = false;
        try {
            em.remove(object);
            em.getTransaction().commit();
            ret = true;
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
            return ret;
        }
    }

    public Lote leer(Lote object) {
        EntityManager em = emf.createEntityManager();
        Lote lote = null;
        Query q = em.createQuery("SELECT l FROM Lote l"
                + "WHERE l.id = :id")
                .setParameter("id", object.getId());
        try {
            lote = (Lote) q.getSingleResult();
        } catch (NoResultException e) {
            lote = null;
        } catch (NonUniqueResultException e) {
            lote = (Lote) q.getResultList().get(0);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            em.close();
            return lote;
        }
    }

    public boolean actualizar(Lote object, Lote nuevoObjeto) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        boolean ret = false;
        try {
            object = leer(object);
            
            object.setCantidad(nuevoObjeto.getCantidad());
            object.setFechadeVencimiento(nuevoObjeto.getFechadeVencimiento());
            object.setNumeroLote(nuevoObjeto.getNumeroLote());
            
            em.merge(object);
            em.getTransaction().commit();
            ret = true;
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
            return ret;
        }
    }
    
}
